package com.yide.myworld.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSONObject;
import com.yide.myworld.domain.SecurityCheckFileDto;
import com.yide.myworld.domain.SecurityCheckImageDto;
import com.yide.myworld.domain.SecurityCheckTextDto;
import com.yide.myworld.exception.ApiException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 风控管理平台
 *
 * @author d
 * @date 2023/1/4 18:41
 */
@Service
public class SecurityService {

    @Value("${tianmcloud.security.url:http://security-test.tianmcloud.top}")
    private String securityUrl;
    @Value("${tianmcloud.security.appId:23010586961951}")
    private String appId;
    @Value("${tianmcloud.security.appSecret:c4189ac89596382b2ac8f2f088edf84f}")
    private String appSecret;

    private String common(String url, List<NameValuePair> nvps) {
        String json;
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            List<NameValuePair> signs = new ArrayList<>();
            signs.addAll(nvps);
            signs.add(new BasicNameValuePair("appid", appId));
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            signs.add(new BasicNameValuePair("timestamp", timestamp));
            signs.sort(Comparator.comparing(NameValuePair::getName, Comparator.reverseOrder()));
            String str = "";
            JSONObject jsonObject = new JSONObject();
            for (NameValuePair sign : signs) {
                str += sign.getName() + sign.getValue();
            }
            for (NameValuePair nvp : nvps) {
                jsonObject.put(nvp.getName(), nvp.getValue());
            }
            str += appSecret;
            MD5 md5 = new MD5();
            String sign = md5.digestHex(str);
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            httpPost.addHeader("sign", sign);
            httpPost.addHeader("appid", appId);
            httpPost.addHeader("timestamp", timestamp);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            //设置请求的参数

            String param = jsonObject.toString();
            StringEntity stringEntity = new StringEntity(param, "utf-8");
            stringEntity.setContentType("text/json");

            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            json = EntityUtils.toString(response.getEntity(), "utf-8");
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 图片审核
     *
     * @return
     */
    public String checkImage(SecurityCheckImageDto dto) {
        String url = securityUrl + "/api/content/check/image";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("content", dto.getContent()));
        nvps.add(new BasicNameValuePair("content_origin", dto.getContent_origin()));
        nvps.add(new BasicNameValuePair("channel_id","用户头像"));
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("action_time", dto.getAction_time()));
        nvps.add(new BasicNameValuePair("ip", dto.getIp()));
        nvps.add(new BasicNameValuePair("app_key_id", dto.getApp_key_id()));
        nvps.add(new BasicNameValuePair("device_id", ""));
        nvps.add(new BasicNameValuePair("room_id", ""));
        nvps.add(new BasicNameValuePair("params", "{}"));

        //请求网易云服务端
        return common(url, nvps);
    }

    /**
     * 文本审核
     *
     * @return
     */
    public String checkText(SecurityCheckTextDto dto) {
        String url = securityUrl + "/api/content/check/text";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("content", dto.getContent()));
        nvps.add(new BasicNameValuePair("content_origin", dto.getContent_origin()));
        nvps.add(new BasicNameValuePair("channel_id", "公告"));
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("action_time", dto.getAction_time()));
        nvps.add(new BasicNameValuePair("ip", dto.getIp()));
        nvps.add(new BasicNameValuePair("app_key_id", dto.getApp_key_id()));
        nvps.add(new BasicNameValuePair("device_id", ""));
        nvps.add(new BasicNameValuePair("room_id", ""));
        nvps.add(new BasicNameValuePair("params", "{}"));


        //请求网易云服务端
        return common(url, nvps);
    }

    /**
     * 音频文件审核
     *
     * @param dto
     * @return
     */
    public String checkFile(SecurityCheckFileDto dto) {
        String url = securityUrl + "/api/content/check/audio/file";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("content", dto.getContent()));
        nvps.add(new BasicNameValuePair("content_origin", dto.getContent_origin()));
        nvps.add(new BasicNameValuePair("channel_id", "音频文件"));
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("action_time", dto.getAction_time()));
        nvps.add(new BasicNameValuePair("ip", dto.getIp()));
        nvps.add(new BasicNameValuePair("app_key_id", dto.getApp_key_id()));
        nvps.add(new BasicNameValuePair("device_id", ""));
        nvps.add(new BasicNameValuePair("room_id", ""));
        nvps.add(new BasicNameValuePair("params", "{}"));

        //请求网易云服务端
        return common(url, nvps);
    }

}